package com.downbox.controller;

import com.downbox.dto.R;
import com.downbox.dto.SubmitReq;
import com.downbox.dto.SubmitResp;
import com.downbox.repository.ContributionRepository;
import com.downbox.security.UserContext;
import com.downbox.service.ContributionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 投稿控制器 - 处理/contribution路径的接口
 */
@RestController
@RequestMapping("/contribution")
@Tag(name = "投稿相关接口")
public class ContributionController {

    private static final Logger logger = LoggerFactory.getLogger(ContributionController.class);
    
    @Autowired
    private ContributionRepository contributionRepository;

    @Autowired
    private ContributionService contributionService;

    @GetMapping("/status")
    @Operation(summary = "获取投稿状态")
    public R<Map<String, Object>> getContributionStatus() {
        Long userId = UserContext.getUserId();
        logger.info("查询用户[{}]的投稿状态", userId);
        
        // 从数据库查询实际投稿数量
        long contributionCount = contributionRepository.countByUid(userId);
        logger.info("用户[{}]的投稿数量: {}", userId, contributionCount);
        
        Map<String, Object> data = new HashMap<>();
        data.put("hasContribution", contributionCount > 0);
        data.put("contributionCount", contributionCount);
        data.put("message", contributionCount > 0 ? "已有投稿记录" : "暂无投稿记录");
        return R.success(data);
    }
    
    @GetMapping("/test")
    @Operation(summary = "测试数据库连接")
    public R<Map<String, Object>> testDatabaseConnection() {
        logger.info("执行数据库连接测试");
        
        try {
            // 测试数据库连接
            long totalCount = contributionRepository.count();
            logger.info("数据库连接成功，总投稿数: {}", totalCount);
            
            Map<String, Object> data = new HashMap<>();
            data.put("databaseConnected", true);
            data.put("totalContributions", totalCount);
            data.put("message", "数据库连接正常");
            return R.success(data);
        } catch (Exception e) {
            logger.error("数据库连接失败: {}", e.getMessage(), e);
            
            Map<String, Object> data = new HashMap<>();
            data.put("databaseConnected", false);
            data.put("errorMessage", e.getMessage());
            data.put("message", "数据库连接失败");
            return R.success(data); // 使用success返回错误信息，避免前端处理错误
        }
    }

    @PostMapping("/submit")
    @Operation(summary = "提交投稿")
    public R<Map<String, Object>> submitContribution(@Valid @RequestBody SubmitReq req) {
        Long userId = UserContext.getUserId();
        logger.info("接收到用户[{}]的投稿请求", userId);
        
        // 调用服务层提交投稿
        logger.info("调用服务层处理投稿请求");
        SubmitResp resp = contributionService.submitContribution(userId, req);
        
        logger.info("投稿处理完成，服务层返回ID：{}", resp.getId());
        
        // 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("submitSuccess", true);
        data.put("message", "投稿成功");
        data.put("contributionId", resp.getId()); // 添加投稿ID到返回数据中
        
        logger.info("返回投稿成功响应给客户端");
        return R.success(data);
    }
}